﻿var Group =
{
  replyId: -1,
  groupId: -1,
  parentMessage: '',
  url: null,
  lnkChk: null,
  name: null,
  about: null,
  groupVisibility: null,
  groupMembership: null,
  isAutoApprove: null,
  membersCanInvite: null,
  message: null,
  messageDelete: null,
  btn: null,
  btnDelete: null,

  initNewEdit: function() {
    Group.url = $("#divGroupCreate #txtUrl");
    Group.lnkChk = $("#divGroupCreate #lnkCheckAvail");
    Group.name = $("#divGroupCreate #txtName");
    Group.about = $("#divGroupCreate #txtAbout");
    Group.groupVisibility = $("#divGroupCreate input[@name=groupvisibility]:checked");
    Group.groupMembership = $("#divGroupCreate input[@name=groupmembership]:checked");
    Group.isAutoApprove = $("#divGroupCreate input[name=isAutoApprove]");
    Group.membersCanInvite = $("#divGroupCreate input[name=membersCanInvite]");
    Group.message = $("#divGroupCreate #infoMessage");
    Group.messageDelete = $("#divGroupCreate #deleteMessage");
    Group.btn = $("#divGroupCreate #btnSubmit");
    Group.btnDelete = $("#divGroupCreate #btnDelete");
  },
  initNew: function() {
    Group.initNewEdit();
    Group.name.alphanumeric({ allow: " " });
    Group.url.alphanumeric({ allow: "_" });
    Group.url.focus();
    Group.lnkChk.show();
       Group.btn.val("create group");
  },

  initEdit: function() {
    Group.initNewEdit();
    Group.name.alphanumeric({ allow: " " });
    Group.url.alphanumeric({ allow: "_" });
    Group.url.attr("disabled", "disabled");
    Group.lnkChk.hide();
    Group.name.focus();
    Group.btn.val("save changes");
    Group.btn.val("save changes");
  },

  create: function() {
    if (!Group.validateBeforeSave()) return;

    Group._showMessage(Group.message, "creating group...", false);
    Group.btn.attr("disabled", "disabled");

    $.ajax({
      type: "POST",
      dataType: "json",
      url: "/group/create",
      data: { url: Group.url.val(),
        name: Group.name.val(),
        about: Group.about.val(),
        groupVisibility: Group.groupVisibility.val(),
        groupMembership: Group.groupMembership.val(),
        isAutoApprove: Group.isAutoApprove.is(":checked"),
        membersCanInvite: Group.membersCanInvite.is(":checked")
      },
      success: function(result) {
        Group.afterSave(result);
      },
      error: function(error) {
        Group.btn.removeAttr("disabled");
        Group.message.hide();
        Group.message.addClass("hilite").fadeIn(1000);
        Group._showMessage(Group.message, "An unexpected error has occurred while saving.", true);
      }
    });
  },

  edit: function(groupid) {
    if (!Group.validateBeforeSave()) return;

    Group._showMessage(Group.message, "saving changes...", false);
    Group.btn.attr("disabled", "disabled");

    $.ajax({
      type: "POST",
      dataType: "json",
      url: "/group/update",
      data: {
        groupid: groupid,
        url: Group.url.val(),
        name: Group.name.val(),
        about: Group.about.val(),
        groupVisibility: Group.groupVisibility.val(),
        groupMembership: Group.groupMembership.val(),
        isAutoApprove: Group.isAutoApprove.is(":checked"),
        membersCanInvite: Group.membersCanInvite.is(":checked")
      },
      success: function(result) {
        Group.afterSave(result);
      },
      error: function(error) {
        Group.btn.removeAttr("disabled");
        Group.message.hide();
        Group.message.addClass("hilite").fadeIn(1000);
        Group._showMessage(Group.message, "An unexpected error has occurred while saving.", true);
      }
    });
  },

  destroy: function(groupid) {
    if (!confirm("Are you sure you want to delete this group?"))
      return;

    Group._showMessage(Group.messageDelete, "deleting group...", false);
    Group.btn.attr("disabled", "disabled");
    Group.btnDelete.attr("disabled", "disabled");
    $.ajax({
      type: "POST",
      dataType: "json",
      url: "/group/destroy",
      data: {
        groupid: groupid
      },
      success: function(result) {
        Group.btn.removeAttr("disabled");
        Group.btnDelete.removeAttr("disabled");
        if (result.isSuccessful == true) {
          window.location = "/group/";
        }
        else {
          Group.messageDelete.addClass("hilite").fadeIn(1000);
          Group._showMessage(Group.messageDelete, result.errorMessage, true);
        }
      },
      error: function(error) {
        Group.btn.removeAttr("disabled");
        Group.btnDelete.removeAttr("disabled");
        Group.messageDelete.hide();
        Group.messageDelete.addClass("hilite").fadeIn(1000);
        Group._showMessage(Group.messageDelete, "An unexpected error has occurred while saving.", true);
      }
    });
  },

  afterSave: function(result) {
    Group.btn.removeAttr("disabled");
    Group.message.hide();

    if (result.isSuccessful == true) {
      window.location = "/group/" + Group.url.val();
    }
    else {
      Group.message.addClass("hilite").fadeIn(1000);
      Group._showMessage(Group.message, result.errorMessage, true);
    }
  },

  validateBeforeSave: function() {
    $("#divGroupCreate div.validator").hide();
    $("#divGroupCreate div.message").hide();
    $("#divGroupCreate div").removeClass("errorField");

    var isValid = true;
    if ($.trim(Group.url.val()).length < 4) {
      Group._showFieldError("#divGroupCreate #valUrl", "* Url should be at least 4 characters long");
      isValid = false;
    }
    if ($.trim(Group.url.val()).length < 1) {
      Group._showFieldError("#divGroupCreate #valUrl", "* required");
      isValid = false;
    }
    if ($.trim(Group.url.val()).length > 50) {
      Group._showFieldError("#divGroupCreate #valUrl", "Url is too long");
      isValid = false;
    }
    if ($.trim(Group.name.val()).length < 1) {
      Group._showFieldError("#divGroupCreate #valName", "* required");
      isValid = false;
    }

    if ($.trim(Group.name.val()).length > 100) {
      Group._showFieldError("#divGroupCreate #valName", "Name is too long");
      isValid = false;
    }

    if ($.trim(Group.about.val()).length > 500) {
      Group._showFieldError("#divGroupCreate #valAbout", "'About' is too long");
      isValid = false;
    }
    return isValid;
  },

  join: function(url, groupid, userid) {
    var lnk = $("#lnkGroupJoin");
    var message = $("#lnkJoinStatus");
    lnk.hide("fast");
    message.removeClass("hilite");
    message.hide();
    Group._showMessage(message, "Joining...");
    $.ajax({
      type: "POST",
      dataType: "json",
      url: "/group/joinsubmit",
      data: { groupid: groupid,
        userid: userid
      },
      success: function(result) {
        if (result.isSuccessful == true) {
          window.location = "/group/" + url;
        }
        else {
          lnk.show("fast");
          message.addClass("hilite").fadeIn(1000);
          Group._showMessage(message, result.errorMessage, true);
        }
      },
      error: function(error) {
        lnk.show("fast");
        message.addClass("hilite").fadeIn(1000);
        Group._showMessage(message, "An unexpected error has occurred while saving.", true);
      }
    });
  },

  leave: function(url, groupid, userid) {
    if (!confirm("Are you sure you want to leave this group?"))
      return;

    var lnk = $("#lnkGroupLeave");
    var message = $("#lnkLeaveStatus");
    lnk.hide("fast");
    message.removeClass("hilite");
    message.hide();
    Group._showMessage(message, "Leaving...");
    $.ajax({
      type: "POST",
      dataType: "json",
      url: "/group/leavesubmit",
      data: { groupid: groupid,
        userid: userid
      },
      success: function(result) {
        if (result.isSuccessful == true) {
          window.location = "/group/" + url;
        }
        else {
          lnk.show("fast");
          message.addClass("hilite").fadeIn(1000);
          Group._showMessage(message, result.errorMessage, true);
        }
      },
      error: function(error) {
        lnk.show("fast");
        message.addClass("hilite").fadeIn(1000);
        Group._showMessage(message, "An unexpected error has occurred while saving.", true);
      }
    });
  },

  approve: function(groupid, userid, isApprove) {
    var divUser = $("#app" + userid);

    var action;
    if (isApprove)
      action = "/group/approve";
    else
      action = "/group/reject";

    $.ajax({
      type: "POST",
      dataType: "json",
      url: action,
      data: { userid: userid, groupid: groupid },
      success: function(result) {
        if (result.isSuccessful == true) {
          divUser.addClass("hilite").fadeOut("fast");
          document.location.reload();
        }
        else {
          alert(result.errorMessage);
        }
      },
      error: function(error) {
        alert("An unexpected error has occurred.");
      }
    });
  },

  postMessage: function(groupid) {
    var msg = $('#message').val();
    Group._showMessage($("#createMessage"), "Sending message...", false);

    $.ajax({
      type: "POST",
      dataType: "json",
      url: "/group/postmessage",
      data: { message: msg, groupid: groupid },
      success: function(result) {
        if (result.isSuccessful) {
          $('#message').val("");
          $("#createMessage").hide("slow");
          window.location.reload();
        } else {
          Group._showMessage($("#createMessage"), result.errorMessage, true);
          $("#createMessage").text(result.errorMessage).show();
        }
      },
      error: function(result) {
        $("#createMessage").text("An unexpected error occurred.").show();
      }
    });
  },

  deleteMessage: function(msgid) {
    if (confirm("Are you sure you want to delete this message?")) {
      $.ajax({
        type: "POST",
        dataType: "json",
        url: "/group/deletemessage",
        data: { messageId: msgid },
        success: function(result) {
          if (result.isSuccessful) {
            $("#gmsgview-" + msgid).addClass("hilite").fadeOut(1000);
          } else {
            alert(result.errorMessage);
          }
        },
        error: function(result, status) {
          alert("An unexpected error occurred.");
        }
      });
    }
  },

  showReply: function(groupid, id) {
    Group.replyId = id;
    Group.groupId = groupid;
    $("#parentMessage #msgHtml").html(
                            $("#gmsgview-" + id + " #msgHtml").html());
    $("#divReplyBox").modal();
    $("#replyMessage").focus();
  },

  hideReply: function() {
    Group.replyId = -1;
    Group.parentMessage = "";
    $("#replyMessage").val("");
    $.modal.close();
  },

  reply: function() {
    var msg = $("#replyMessage").val();
    var msgId = Group.replyId;
    var groupid = Group.groupId;

    $("#replyStatus").text("Sending reply...").show();

    $.ajax({
      type: "POST",
      dataType: "json",
      url: "/group/reply",
      data: { groupid: groupid,
        messageid: msgId,
        Message: msg
      },
      success: function(result) {
        if (result.isSuccessful) {
          $("#replyMessage").val("");
          window.location.reload();
        } else {
          $("#replyStatus").text(result.errorMessage).show();
        }
      },
      error: function(result) {
        $("#replyStatus").text("Unexpected error").show();
      }
    });
  },

  saveSettings: function(url, groupid, userid) {
    var message = $("#divGroupSettings #infoMessage");
    var btn = $("#divGroupSettings #btnSubmit");
    Group._showMessage(message, "saving changes...", false);
    btn.attr("disabled", "disabled");
    $.ajax({
      type: "POST",
      dataType: "json",
      url: "/group/" + url + "/savesettings",
      data: { groupid: groupid,
        userid: userid,
        notifyOnMessage: $('#notifyOnMessage').is(":checked"),
        notifyOnReply: $('#notifyOnReply').is(":checked"),
        notifyOnJoin: $('#notifyOnJoin').is(":checked"),
        notifyOnLeave: $('#notifyOnLeave').is(":checked"),
        notifyOnPending: $('#notifyOnPending').is(":checked")
      },
      success: function(result) {
        btn.removeAttr("disabled");
        message.hide();
        if (result.isSuccessful == true) {
          window.location = "/group/" + url;
        }
        else {
          message.addClass("hilite").fadeIn(1000);
          Group._showMessage(message, result.errorMessage, true);
        }
      },
      error: function(result) {
        btn.removeAttr("disabled");
        message.hide();
        message.addClass("hilite").fadeIn(1000);
        Group._showMessage(message, "An unexpected error has occurred while saving.", true);
      }
    });
  },

  checkAvailability: function() {
    //need to refactor group validation
    var url = $("#divGroupCreate #txtUrl");
    $("#divGroupCreate #valUrl").hide();
    $("#divGroupCreate div").removeClass("errorField");

    if ($.trim(url.val()).length < 1) {
      Group._showFieldError("#divGroupCreate #valUrl", "* required");
      return;
    }
    if ($.trim(url.val()).length < 4) {
      Group._showFieldError("#divGroupCreate #valUrl", "* Url should be at least 4 characters long");
      return;
    }
    if ($.trim(url.val()).length > 50) {
      Group._showFieldError("#divGroupCreate #valUrl", "Url is too long");
      return;
    }

    $.ajax({
      type: "POST",
      dataType: "json",
      url: "/group/CheckAvailability",
      data: { url: url.val() },
      success: function(result) {
        if (result.isAvailable)
          Group._showMessage("#divGroupCreate #valAvail", "available", false);
        else
          Group._showFieldError("#divGroupCreate #valAvail", "not available");
      },
      error: function(error) {
        alert("error");
      }
    });
  },

  _showMessage: function(e, msg, err) {
    if (err) {
      $(e).css("color", '#ff0000');
    }
    else {
      $(e).css("color", '');
    }
    $(e).text(msg);
    $(e).show();
  },

  _showFieldError: function(e, msg) {
    $(e).text(msg).show();
    $(e).parent().addClass("errorField");
  }
}